﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Prod_Default : System.Web.UI.Page
{
    enum MailOptions
    {
        NoMail = 0,
        NoMailbox = 1,
        Mailbox = 2       
    };   
    
    protected void Page_Load(object sender, EventArgs e)
    {        
        lblAuthInfo.Text = Request.LogonUserIdentity.Name;

        if (!IsPostBack) 
        {
            ViewState["mailOptionChoice"] = (int)MailOptions.Mailbox;            
            txtUserMail.Visible = false;
            lbltxtUserMail.Visible = false;
            reqExpValMailaddr.Enabled = false;
            regexCusValEmail.Enabled = false;
            fill_ExOwaPols();
            fill_ExDBs();
            fill_OUs();
            fill_ExMailboxRetPols();
            fill_DFSHomes();
            clear_fields();
        }
        
    }

    protected void formatHTMLTag(System.Web.UI.WebControls.Label intag, int inrslt)
    {
       
        string badrslt = "<span class=\"badrslt\"> &#x2717; </span>";
        string goodrslt = "<span class=\"goodrslt\"> &#x2713; </span>";

        intag.Text = intag.Text.Replace(badrslt, "");
        intag.Text = intag.Text.Replace(goodrslt, "");
                
        if (inrslt == 1)
            intag.Text += badrslt;        
        else
            intag.Text += goodrslt;                  

    }  

    protected void chkFilterOU_CheckedChanged(object sender, EventArgs e)
    {
        fill_OUs();
    }

    protected void reqValCustOU_ServerValidate(object source, ServerValidateEventArgs args)
    {
        
        int rslt;             

        if (!args.Value.Contains("Please"))
        {
            args.IsValid = true;
            rslt = 0;            
        }
        else
        {            
            args.IsValid = false;
            drpdlstOUs.Focus();            
            rslt = 1;            
        }

        System.Web.UI.WebControls.Label intag = lbldrpdlstOUs;
        formatHTMLTag(intag, rslt);

    }

    protected void reqValCustEXDB_ServerValidate(object source, ServerValidateEventArgs args)
    {
        
        int rslt;
        
        if (!args.Value.Contains("Please"))
        {
            args.IsValid = true;
            rslt = 0;            
        }
        else
        {
            args.IsValid = false;
            rslt = 1;
            reqValCustEXDB.ErrorMessage = "Invalid.";
            drpdlstExDBs.Focus();            
        }

        System.Web.UI.WebControls.Label intag = lbltxtUserMail;
        formatHTMLTag(intag, rslt);

    }

    protected void reqCustFullName_ServerValidate(object source, ServerValidateEventArgs args)
    {
        int rslt;
        
        if (!args.Value.Contains("conflict") && (args.Value.Length > 5))
        {
            args.IsValid = true;
            rslt = 0;
        }
        else
        {
            txtUserFullName.Focus();
            args.IsValid = false;
            reqValFullName.ErrorMessage = "Fullname not valid.";            
            rslt = 1;

        }

        System.Web.UI.WebControls.Label intag = lbldrpdlstOUs;
        formatHTMLTag(intag, rslt);
    }

    protected void regexCusValEmail_SrvValidate(out int retvalcusmail)
    {
           
        string mailaddr = txtUserMail.Text;
        //Customize here.
        if ((mailaddr.Contains("@ads.")) || (mailaddr.Contains("@ads-")) || (mailaddr.Contains("@adsi")))
        {
            retvalcusmail = 1;
            txtUserMail.Focus();
        }
        else
        {
            retvalcusmail = 0;            
        }

        System.Web.UI.WebControls.Label intag = lbltxtUserMail;
        formatHTMLTag(intag, retvalcusmail);

    }

    protected void fill_OUs()
    {
        string objContentMsg = "";
        int retval;
        int objContentNO;
        bool OUfiltered;
        drpdlstOUs.Items.Clear();

        if (chkFilterOU.Checked)
            OUfiltered = true;
        else
            OUfiltered = false;

        ADrwInfo ADrwinfoO = new ADrwInfo();

        List<string> rtnList = ADrwinfoO.RetOUs(ref objContentMsg, out retval, out objContentNO, OUfiltered);

        foreach (string itm in rtnList)
        {
            string OUname = "";
            //Customize here.
            OUname = itm.Replace("DC=ads", "").Replace("DC=loc", "");
            OUname = OUname.Replace(",", " ");
            OUname = Regex.Replace(OUname, "..=", "", RegexOptions.IgnoreCase);
            drpdlstOUs.Items.Add(new ListItem(OUname, itm));
        }
    }

    protected void fill_ExDBs()
    {
        drpdlstExDBs.Items.Clear();
        int retval;
        string objContentMsg = "";

        FSGetFileContent fileCont = new FSGetFileContent();
        fileCont.SourceFile = WbGetParams.ExchangeDatabaseNamesFile;

        List<string> rtnList = fileCont.rtnValues(out retval, ref objContentMsg);
        foreach (string itm in rtnList)
            drpdlstExDBs.Items.Add(new ListItem(itm, itm));
    }

    protected void fill_ExOwaPols()
    {
        drpdlstExMbOwaPols.Items.Clear();
        int retval;
        string objContentMsg = "";

        FSGetFileContent fileCont = new FSGetFileContent();
        fileCont.SourceFile = WbGetParams.ExchangeOwaPolicyFile;

        List<string> rtnList = fileCont.rtnValues(out retval, ref objContentMsg);
        foreach (string itm in rtnList)
            drpdlstExMbOwaPols.Items.Add(new ListItem(itm, itm));
    }
    
    protected void fill_ExMailboxRetPols()
    {
        drpdlstExMbRetPols.Items.Clear();
        int retval;
        string objContentMsg = "";

        FSGetFileContent fileCont = new FSGetFileContent();
        fileCont.SourceFile = WbGetParams.ExchangeMailboxRetentionFile;

        List<string> rtnList = fileCont.rtnValues(out retval, ref objContentMsg);
        foreach (string itm in rtnList)
            drpdlstExMbRetPols.Items.Add(new ListItem(itm, itm));
    }

    protected void fill_DFSHomes()
    {
        drpdlstDFSHome.Items.Clear();
        int retval;
        string objContentMsg = "";

        FSGetFileContent fileCont = new FSGetFileContent();
        fileCont.SourceFile = WbGetParams.DFSHomesFile;

        List<string> rtnList = fileCont.rtnValues(out retval, ref objContentMsg);
        foreach (string itm in rtnList)
        {
            string[] tmp = itm.Split(',');
            string sname = tmp[0];
            drpdlstDFSHome.Items.Add(new ListItem(sname, tmp[1]));
        }
    }    

    protected void clear_fields()
    {        
        lblLoadExistUsrRslt.Text = "";
        txtExistUsrId.Text = "";          
        txtUserFirstName.Text = "";
        txtUserFullName.Text = "";
        txtUserId.Text = "";
        txtUserId.Focus();
        txtUserLastName.Text = "";        
        txtUsrPersonnelno.Text = "";
        txtUsrPwd.Text = "";
        txtUsrFaxDir.Text = "";
        txtUserCity.Text = "";
        txtUserMail.Text = "";
        txtUserPhone.Text = "";
        txtUserZIP.Text = "";
        txtUserSkype.Text = "";
        drpdlstExDBs.SelectedValue = "_Please choose:";
        drpdlstDFSHome.SelectedValue = "0000";
        lstUserGroupsQ.Items.Clear();
        lbltxtUserId.Text = "User-ID:";
        lbltxtUserFullName.Text = "Fullname:";
        lbltxtUsrPersonnelno.Text = "Personnel Number:";
        lbltxtUserMail.Text = "External E-Mailaddress:";
        lbldrpdlstOUs.Text = "Organizational Unit:";
        lbldrpdlstExDBs.Text = "Mailbox Database:";
        txtgroupsearch.Text = "";
        txtqrycompanykey.Text = "";
        drpdlstOUs.SelectedValue = "_Please choose:";
        colorrefresh();    
    }

    protected void colorrefresh()
    {
        colorous();
        colormodu(drpdlstExDBs);
        colormodu(drpdlstExMbOwaPols);
        colormodu(drpdlstExMbRetPols);
        colormodu(drpdlstDFSHome);
    }

    protected void lbtnLoadExistUsr_Click(object sender, EventArgs e)
    {

        string uiUserID = WbVarious.RmInvalidChrs(txtExistUsrId.Text);
        if (uiUserID.Length < 3)
        {
            lblLoadExistUsrRslt.Text = "Search not performed, name too short.";            
            System.Web.UI.WebControls.Label intag = lblLoadExistUsrRslt;            
            formatHTMLTag(intag, 1);
        }
        else
        {
            lblExistUsrFullName.Text = "";

            StringBuilder sb = new StringBuilder();
            
            string objContentMsg = "";
            ADrwInfo ADrwinfoO = new ADrwInfo();
            int retval;
            int objContentNO;
            string objsearchfilter = "user";
            ADobjInfo adobjui = new ADobjInfo();

            lstUserGroupsQ.Items.Clear();                                 
            
            adobjui.ADUserID = uiUserID.Trim();

            List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);                         
            
            if (retval == 0 && objContentNO > 0)
            {
                
                lblLoadExistUsrRslt.Text = "User found.";
                lblExistUsrFullName.Text = rtnList[0].ADfullName;
                
                System.Web.UI.WebControls.Label intag = lblLoadExistUsrRslt;                
                formatHTMLTag(intag, 0);
                
                txtUserCity.Text = rtnList[0].ADCity;
                txtUserZIP.Text = rtnList[0].ADpostalCode;
                txtUserStreet.Text = rtnList[0].ADstreetAddress;                
                
                if (rtnList[0].ADmemberOf.Count > 0)
                {
                    foreach (string itm in rtnList[0].ADmemberOf)
                    {
                        string[] tmp = itm.Split(',');
                        string lstitm = tmp[0].Replace("cn=", "").Replace("CN=", "");                        
                        sb.Append(lstitm).Append(" ");
                        lstUserGroupsQ.Items.Add(new ListItem(lstitm, itm));
                    }            
                }
                
                string OUval = rtnList[0].ADdistinguishedName;
                OUval = OUval.Replace(OUval.Substring(0, OUval.IndexOf(",OU=")),"");
                OUval = OUval.TrimStart(',');
                
                string OUvalr = "";
                string[] OUvalrtmp = OUval.Split(',');
                var tmpOU = OUvalrtmp.Reverse();
                foreach (string OU in tmpOU)
                    OUvalr += OU + ',';
                OUvalr = OUvalr.TrimEnd(',');                              

                if (OUval.Contains("dministrative"))                                    
                    drpdlstOUs.SelectedValue = "_Please choose:";
                else                
                    drpdlstOUs.SelectedValue = OUvalr;

                txtqrycompanykey.Text = rtnList[0].ADcompanyKey;              
                                
            }                
            else
            {
                lblLoadExistUsrRslt.Text = "User not found.";                
                System.Web.UI.WebControls.Label intag = lblLoadExistUsrRslt;                
                formatHTMLTag(intag, 1);
            }
        }
        drpdlstDFSHome.SelectedValue = "0000";
        colorrefresh();
    }

    protected void collectInfoFromHTML(out ADobjInfo adobjout)
    {

        ADobjInfo adobj = new ADobjInfo();

        List<string> memberOf = new List<string>();
        if (lstUserGroupsQ.Items.Count > 0)
        {
            for (int i = 0; i < lstUserGroupsQ.Items.Count; i++)
            {
                ListItem item = lstUserGroupsQ.Items[i];
                memberOf.Add(item.Value);
            }
            adobj.ADmemberOf = memberOf;
        }
        else
        {
            List<string> nogroups = new List<string>();
            nogroups.Add("");
            adobj.ADmemberOf = nogroups;
        }  

        string uCompanyKey = WbVarious.RmInvalidChrs(htxtCompanyKey.Value);
        if (uCompanyKey.Contains(','))
        {
            string[] tmpck = uCompanyKey.Split(',');
            adobj.ADcompanyKey = tmpck[0];
        }
        else
        {
            adobj.ADcompanyKey = "";
        }        

        adobj.ADUserID = txtUserId.Text.Trim();        
        adobj.ADdistinguishedName = drpdlstOUs.SelectedValue;
        adobj.ADExOwaPol = drpdlstExMbOwaPols.SelectedValue;
        adobj.ADExMBRetPol = drpdlstExMbRetPols.SelectedValue;
        adobj.ADExDB = drpdlstExDBs.SelectedValue;     
        adobj.ADfirstName = WbVarious.RmInvalidChrs(txtUserFirstName.Text);
        adobj.ADfamilyName = WbVarious.RmInvalidChrs(txtUserLastName.Text);
        adobj.ADfullName = WbVarious.RmInvalidChrs(txtUserFullName.Text);
        
        adobj.ADpersonnelNumber = txtUsrPersonnelno.Text.Trim();

        if (!String.IsNullOrEmpty(htxtdate.Value))
        {
            string[] tmpdate = htxtdate.Value.Split('-');
            int ayear = int.Parse(tmpdate[0]);
            int amonth = int.Parse(tmpdate[1]);
            int aday = int.Parse(tmpdate[2]);

            DateTime dt = new DateTime(ayear, amonth, aday);

            if (dt >= DateTime.Today)
                adobj.ADExperiationDate = dt;
            else
                adobj.ADExperiationDate = DateTime.Today;
        }         
        
        if (drpdlstDFSHome.SelectedValue != "0000")
            adobj.ADHomeDirve = drpdlstDFSHome.SelectedValue + '\\' + txtUserId.Text.Trim();
        else
            adobj.ADHomeDirve = "";

        string uCity = WbVarious.RmInvalidChrs(txtUserCity.Text);
        string uFax = WbVarious.RmInvalidChrsV2(txtUsrFaxDir.Text);
        string uMail = txtUserMail.Text.Trim();
        string uPhone = txtUserPhone.Text.Trim();
        string uZip = WbVarious.RmInvalidChrs(txtUserZIP.Text);
        string uSkype = WbVarious.RmInvalidChrs(txtUserSkype.Text);
        string uStreet = WbVarious.RmInvalidChrs(txtUserStreet.Text);
        string uPwd = WbVarious.RmInvalidChrs(txtUsrPwd.Text);

        if (!String.IsNullOrEmpty(uCity))
            adobj.ADCity = uCity;

        if (!String.IsNullOrEmpty(uFax))
            adobj.ADproxyAddresses = uFax;

        if (!String.IsNullOrEmpty(uMail))
            adobj.ADMail = uMail;

        if (!String.IsNullOrEmpty(uPhone))
            adobj.ADtelelphoneNumber = uPhone;

        if (!String.IsNullOrEmpty(uZip))
            adobj.ADpostalCode = uZip;

        if (!String.IsNullOrEmpty(uSkype))
            adobj.ADSkype = uSkype;

        if (!String.IsNullOrEmpty(uStreet))
            adobj.ADstreetAddress = uStreet;

        if (!String.IsNullOrEmpty(uPwd))
            adobj.ADPwd = uPwd;

        string uitimezone = htxttimezone.Value;        
        double timezonedif = 0;

        if (!string.IsNullOrEmpty(uitimezone))
        {
            switch (uitimezone)
            {
                case "Europe/Berlin":                    
                    timezonedif = 1;
                    break;
                case "America/Sao_Paulo":                    
                    timezonedif = -3;
                    break;
                case "Asia/Shanghai":                    
                    timezonedif = 8;
                    break;
                case "Pacific/Auckland":                    
                    timezonedif = 12;
                    break;
                case "Asia/Jakarta":                    
                    timezonedif = 7;
                    break;
                case "America/New_York":                    
                    timezonedif = -5;
                    break;
                default:
                    timezonedif = 0;                    
                    break;
            }
        }
        else
        {            
            timezonedif = 0;
        }
        
        adobj.ADTimeOffset = timezonedif;
        adobjout = adobj;

    }

    protected void custValUserID_SrvValidate(out int retvalusrid)
    {
        retvalusrid = 0;
        if (reqExpValUserId.IsValid && reqValUserID.IsValid)
        {
            string objContentMsg = "";
            ADrwInfo ADrwinfoO = new ADrwInfo();
            ADobjInfo adobjui = new ADobjInfo();
            int retval;
            int objContentNO;
            string objsearchfilter = "user";            
            lbltxtUserId.Attributes.Remove("Title");

            adobjui.ADUserID = txtUserId.Text.Trim();

            List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);

            if (retval == 0 && objContentNO > 0)
            {
                lbltxtUserId.Attributes.Add("Title", "Already exists on: " + rtnList[0].ADfullName);   
                txtUserId.Focus();
                retvalusrid = 1;                                                                                     
            }
            else
            {
                lbltxtUserId.Attributes.Add("Title", "UserID is fine.");   
                retvalusrid = 0;                
            }

            System.Web.UI.WebControls.Label intag = lbltxtUserId;
            formatHTMLTag(intag, retvalusrid);

        }
    }

    protected void custValNameExist_SrvValidate(out int retvalname)
    {
        retvalname = 0;
        if (reqValFirstName.IsValid && reqValLastName.IsValid)
        {
            string objContentMsg = "";
            ADrwInfo ADrwinfoO = new ADrwInfo();
            ADobjInfo adobjui = new ADobjInfo();
            int retval;
            int objContentNO;
            string objsearchfilter = "name";
            
            lbltxtUserFullName.Attributes.Remove("Title");
            
            adobjui.ADfullName = WbVarious.RmInvalidChrs(txtUserFullName.Text);

            List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);

            if (retval == 0 && objContentNO > 0)
            {                
                lbltxtUserFullName.Attributes.Add("Title", "Already exists on: " + rtnList[0].ADUserID);                 
                txtUserFullName.Focus();
                retvalname = 1;            
            }
            else
            {
                lbltxtUserFullName.Attributes.Add("Title", "Fullname is fine.");   
                txtUserFullName.Text = WbVarious.RmInvalidChrs(txtUserFullName.Text);
                retvalname = 0;                
            }

            System.Web.UI.WebControls.Label intag = lbltxtUserFullName;
            formatHTMLTag(intag, retvalname);

        }
    }

    protected void custValPersonnelnoExist_SrvValidate(out int retvalpersno)
    {
        retvalpersno = 0;
        if (reqExpValPersonnelNo.IsValid && (!String.IsNullOrEmpty(txtUsrPersonnelno.Text)))
        {
            string objContentMsg = "";
            ADrwInfo ADrwinfoO = new ADrwInfo();
            ADobjInfo adobjui = new ADobjInfo();
            int retval;
            int objContentNO;
            string objsearchfilter = "personnelno";
            adobjui.ADpersonnelNumber = txtUsrPersonnelno.Text.Trim();
                        
            lbltxtUsrPersonnelno.Attributes.Remove("Title");

            List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);

            if (retval == 0 && objContentNO > 0)
            {
                retvalpersno = 1;
                txtUsrPersonnelno.Focus();
                lbltxtUsrPersonnelno.Attributes.Add("Title", "Already exists on: " + rtnList[0].ADfullName);                 
            }
            else
            {
                retvalpersno = 0;
                lbltxtUsrPersonnelno.Attributes.Add("Title", "Personnelnumber is fine.");                 
            }

            System.Web.UI.WebControls.Label intag = lbltxtUsrPersonnelno;
            formatHTMLTag(intag, retvalpersno);

        }
    }

    protected void custValEmail_SrvValidate(out int retvalmail)
    {
        retvalmail = 0;
        if ((reqExpValMailaddr.IsValid) && (!String.IsNullOrEmpty(txtUserMail.Text.Trim())))
        {
            string objContentMsg = "";
            ADrwInfo ADrwinfoO = new ADrwInfo();
            ADobjInfo adobjui = new ADobjInfo();
            int retval;
            int objContentNO;
            string objsearchfilter = "mail";
            adobjui.ADMail = txtUserMail.Text.Trim();            
            List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);

            lbltxtUserMail.Attributes.Remove("Title");            

            if (retval == 0 && objContentNO > 0)
            {                
                retvalmail = 1;
                txtUserMail.Focus();
                lbltxtUserMail.Attributes.Add("Title", "Already exists on: " + rtnList[0].ADfullName);                     
            }
            else
            {
                lbltxtUserMail.Attributes.Add("Title", "E-Mailaddress is fine."); 
                retvalmail = 0;                
            }
        }
    }

    protected void rdbtnlstMailChoice_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (rdbtnlstMailChoice.SelectedIndex)
        {
            case (int)MailOptions.NoMail:
            {
                txtUserMail.Visible = false;
                lbltxtUserMail.Visible = false;
                reqExpValMailaddr.Enabled = false;
                regexCusValEmail.Enabled = false;
                
                drpdlstExDBs.Visible = false;
                lbldrpdlstExDBs.Visible = false;
                reqValCustEXDB.Enabled = false;

                drpdlstExMbOwaPols.Visible = false;
                lbldrpdlstExMbOwaPols.Visible = false;

                drpdlstExMbRetPols.Visible = false;
                lbldrpdlstExMbRetPols.Visible = false;
                ViewState["mailOptionChoice"] = (int)MailOptions.NoMail;
                colorrefresh();                
                break;
            }
            case (int)MailOptions.NoMailbox:
            {
                txtUserMail.Visible = true;
                lbltxtUserMail.Visible = true;
                reqExpValMailaddr.Enabled = true;
                regexCusValEmail.Enabled = true;

                drpdlstExDBs.Visible = false;
                lbldrpdlstExDBs.Visible = false;
                reqValCustEXDB.Enabled = false;

                drpdlstExMbOwaPols.Visible = false;
                lbldrpdlstExMbOwaPols.Visible = false;

                drpdlstExMbRetPols.Visible = false;
                lbldrpdlstExMbRetPols.Visible = false;
                ViewState["mailOptionChoice"] = (int)MailOptions.NoMailbox;
                colorrefresh();
                break;
            }
            case (int)MailOptions.Mailbox:
            {
                txtUserMail.Visible = false;
                lbltxtUserMail.Visible = false;
                reqExpValMailaddr.Enabled = false;
                regexCusValEmail.Enabled = false;

                drpdlstExDBs.Visible = true;
                lbldrpdlstExDBs.Visible = true;
                reqValCustEXDB.Enabled = true;

                drpdlstExMbOwaPols.Visible = true;
                lbldrpdlstExMbOwaPols.Visible = true;

                drpdlstExMbRetPols.Visible = true;
                lbldrpdlstExMbRetPols.Visible = true;
                ViewState["mailOptionChoice"] = (int)MailOptions.Mailbox;
                colorrefresh();
                break;
            }   
        }      

    }

    protected void validateLocal(out int retval)
    {
        retval = 1;
        
        reqValUserID.Validate();
        reqExpValUserId.Validate();
        reqValPwd.Validate();
        reqValFirstName.Validate();
        reqValLastName.Validate();
        reqValCustEXDB.Validate();
        reqExpValPersonnelNo.Validate();
        reqValCustOU.Validate();
        regexCusValEmail.Validate();
        reqValFullName.Validate();

        int retvalcusmail = 0;
        if ((int)ViewState["mailOptionChoice"] == (int)MailOptions.NoMailbox)
            regexCusValEmail_SrvValidate(out retvalcusmail);

        if (retvalcusmail == 0)
            retval = 0;
        else
            retval = 1;

    }

    protected void validateRemote(out int retval)
    {
        retval = 0;
        if (Page.IsValid)
        {
            int retvalname;
            int retvalpersno;
            int retvalusrid;
            int retvalmail;

            custValUserID_SrvValidate(out retvalusrid);
            custValNameExist_SrvValidate(out retvalname);
            custValPersonnelnoExist_SrvValidate(out retvalpersno);

            if (retvalname == 0 && retvalpersno == 0 && retvalusrid == 0)
                retval = 0;
            else
                retval = 1;

            if ((int)ViewState["mailOptionChoice"] == (int)MailOptions.NoMailbox)
            {
                custValEmail_SrvValidate(out retvalmail);
                if (retval == 0 && retvalmail == 0)
                    retval = 0;
                else
                    retval = 1;
            }
            
        }
    }

    protected void lbtnCreateUser_Click(object sender, EventArgs e)
    {

        int retvalSID = 1;
        int retvalremote, retvallocal,  retvaladu, retvaladg, retvalad;
        string objContentMsgMb = "";
        string objContentMsgCas = "";        
        string retSIDMsg = "";
        string usrSID = "";
        string retHomeMsg = "";
        string retMsgACL = "";
        string retServerLives = "";
        string objContentMsgadg = "";
        string objContentMsgadu = "";
        string objContentMsgad = "";        
        
        validateLocal(out retvallocal);
        validateRemote(out retvalremote);        

        if (Page.IsValid && retvalremote == 0 && retvallocal == 0)    
        {

            lbtnCreateUser.Visible = false;

            Dictionary<string, string> AppFeedback = new Dictionary<string, string>();

            if (AppFeedback.ContainsKey("Create_User"))
                AppFeedback.Remove("Create_User");
            if (AppFeedback.ContainsKey("EX_ServerCheck"))
                AppFeedback.Remove("EX_ServerCheck");
            if (AppFeedback.ContainsKey("Verify_User"))
                AppFeedback.Remove("Verify_User");
            if (AppFeedback.ContainsKey("Mailbox_Creation"))
                AppFeedback.Remove("Mailbox_Creation");
            if (AppFeedback.ContainsKey("CASPolicy_Setting"))
                AppFeedback.Remove("CASPolicy_Setting");
            if (AppFeedback.ContainsKey("FS_ServerCheck"))
                AppFeedback.Remove("FS_ServerCheck");
            if (AppFeedback.ContainsKey("FS_FolderCreation"))
                AppFeedback.Remove("FS_FolderCreation");
            if (AppFeedback.ContainsKey("FS_SetFolderACL"))
                AppFeedback.Remove("FS_SetFolderACL");

            ADobjInfo adobjout;
            collectInfoFromHTML(out adobjout);

            ADobjInfo adobj = new ADobjInfo();
            adobj = adobjout;           
            
            ADrwInfo adworkobj = new ADrwInfo();
            adworkobj.CreateUser(out objContentMsgadu, out retvaladu, adobj);            

            if (retvaladu == 0)
            {
                AppFeedback.Add("Create_User", "User-Id: " + adobj.ADUserID + " created.");            

                usrSID = adworkobj.GetUsrSID(adobj.ADUserID, out retvalSID, out retSIDMsg);
            
                if (retvalSID == 0)
                    adobj.ADSID = usrSID;
                else
                    adobj.ADSID = "";                
                
                //ADDING User to Groups
                adworkobj.AddUserToGroups(out objContentMsgadg, out retvaladg, adobj);

                if (AppFeedback.ContainsKey("Add_Groups"))
                    AppFeedback.Remove("Add_Groups");

                if (String.IsNullOrEmpty(objContentMsgadg))
                    AppFeedback.Add("Add_Groups", "Groups added.");                
                else
                    AppFeedback.Add("Add_Groups", objContentMsgadg);              
                                
                //CREATING Homedrive              
                if (chkCrtHomeDrive.Checked == true)
                {
                    bool fsserverReachable = CheckServerReachable(adobj, out retServerLives, "");
                    if (fsserverReachable)
                    {
                        AppFeedback.Add("FS_ServerCheck", "The computer that servers" + adobj.ADHomeDirve + " is reachable.");
                        
                        bool homeCreated = CreateHomeDrive(adobj, out retHomeMsg);
                        if (homeCreated) 
                        {
                            AppFeedback.Add("FS_FolderCreation", adobj.ADHomeDirve + " created." + retHomeMsg);
                            
                            bool aCLSet = SetHomeACL(adobj, out retMsgACL);
                            if (aCLSet)
                            {
                                AppFeedback.Add("FS_SetFolderACL","ACL was set, PLEASE VERIFY!");                                
                            }
                            else
                            {
                                AppFeedback.Add("FS_SetFolderACL", "ACL was not been set." + retMsgACL);                                                                
                            }
                        }
                        else
                        {
                            AppFeedback.Add("FS_FolderCreation", adobj.ADHomeDirve + " not created." + retHomeMsg);                            
                        }
                    }
                    else
                    {
                        AppFeedback.Add("FS_ServerCheck", "The computer that servers" + adobj.ADHomeDirve + " is not reachable.");                        
                    }
                }                               
                
                //CREATING Mailbox
                if ((int)ViewState["mailOptionChoice"] != (int)MailOptions.NoMail)
                {
                    string pexsrv = WbGetParams.ExchangeServerName;
                    string snexsrv = WbGetParams.ExchangeSecondServerName;

                    bool pexsrvReachable = CheckServerReachable(adobj, out retServerLives, pexsrv);
                    bool snexsrvReachable = CheckServerReachable(adobj, out retServerLives, snexsrv);
                    
                    if (pexsrvReachable || snexsrvReachable) 
                    {
                        AppFeedback.Add("EX_ServerCheck", "At least one of the CAS servers: " + pexsrv + " / " +
                           snexsrv + "  is reachable.");               
               
                        if (CheckUserReadiness(adobj))
                        {
                            AppFeedback.Add("Verify_User", "User: " + adobj.ADUserID + " found." );
                            bool mailboxCreated = CreateMailbox(adobj, out objContentMsgMb);                    

                            if (mailboxCreated)
                            {
                                AppFeedback.Add("Mailbox_Creation", "Mailbox created. / Mailaddress set." + objContentMsgMb);
                                if ((int)ViewState["mailOptionChoice"] == (int)MailOptions.Mailbox)
                                {
                                    bool owaSet = SetMailboxCasPoliy(adobj, out objContentMsgCas);
                                    if (owaSet)                            
                                        AppFeedback.Add("CASPolicy_Setting"," OWA policy set.");                            
                                    else
                                        AppFeedback.Add("CASPolicy_Setting", " OWA policy not set.");
                                }                              
                            }
                            else
                            {
                                AppFeedback.Add("Mailbox_Creation", "Mailbox not created." + objContentMsgMb);
                            }
                        }
                        else
                        {
                            AppFeedback.Add("Verify_User", "User: " + adobj.ADUserID + " not found in directory.");                    
                        }
                    }
                    else
                    {
                        AppFeedback.Add("EX_ServerCheck", "Both CAS servers: " +  pexsrv + " and " +
                           snexsrv + " are not available. Mailbox not created.");                        
                    }                    
                }
            }                      
            else
            {
                retvaladg = 1;                
                AppFeedback.Add("Create_User", objContentMsgadu + " Failed.");
            }            
                        
            retvalad = retvaladu + retvaladg;
            objContentMsgad = objContentMsgadu + ' ' + objContentMsgadg;            

            UpdateLog(adobj, retvalad, objContentMsgad);                                
            
            AppFeedbackUI.Visible = true;
            string appfeedback = "";

            foreach (var pair in AppFeedback)                            
                appfeedback += "<tr><td>" + pair.Key + "</td><td>" + pair.Value + "</td></tr>";

            string tblcss = "rslttablegood";
            if (appfeedback.Contains("not") || appfeedback.Contains("Not"))            
                tblcss = "rslttablesoso";
            if (appfeedback.Contains("xception") || appfeedback.Contains("code line"))            
                tblcss = "rslttablebad";                            
            
            lblAppFeedback.Text = "<table class=" + tblcss + ">" + appfeedback + "</table>";
            
            string notifymsg = "<table class=" + tblcss + ">" + appfeedback + "</table>";
            string mailrcp = GetNotifyMailRcpAddr();

            if (!String.IsNullOrEmpty(mailrcp))
            {
                SendNotificationMail(mailrcp, notifymsg);
            }

        }      
    }
    
    protected void lbtnAddGroup_Click(object sender, EventArgs e)
    {
        string tmpin = htxtnewgroup.Value;
        if (!String.IsNullOrEmpty(tmpin))
        {
            if (tmpin.Contains('^'))
            {
                string[] tmparr = tmpin.Split('^');
                ListItem itm = new ListItem("(+) " + tmparr[1].ToString(), tmparr[0].ToString());                                                
                lstUserGroupsQ.Items.Insert(0, itm);
            }
        }
        txtgroupsearch.Text = "";
    }

    protected void lbtnRemoveGroup_Click(object sender, EventArgs e)
    {
        Dictionary<int, string> Groups = new Dictionary<int, string>();

        for (int i = 0; i < lstUserGroupsQ.Items.Count; i++)
        {
            Groups.Add(i, lstUserGroupsQ.Items[i].ToString() + '^' + lstUserGroupsQ.Items[i].Value.ToString());
        }

        int[] grpInd = lstUserGroupsQ.GetSelectedIndices();

        foreach (int i in grpInd)
            Groups.Remove(i);

        lstUserGroupsQ.Items.Clear();

        foreach (var itm in Groups)
        {
            string[] tmp;
            tmp = itm.Value.Split('^');
            lstUserGroupsQ.Items.Add(new ListItem(tmp[0], tmp[1]));
        }            
    }

    protected bool CheckServerReachable(ADobjInfo adobjin, out string objContentMsg, string serverin)
    {
        
        objContentMsg = "";
        string retmsg;
        string serverName;

        if (serverin == "")
        {
            string tmp = adobjin.ADHomeDirve.Substring(2, adobjin.ADHomeDirve.Length - 2);
            serverName = tmp.Substring(0, tmp.IndexOf("\\"));
        }
        else
        {
            serverName = serverin;
        }

        NWvarOps checksrv = new NWvarOps();
        checksrv.SrvName = serverName;

        bool srvlives = checksrv.ServerReachable(out retmsg);
        objContentMsg = retmsg;

        if (srvlives)
            return true;
        else
            return false;
    }

    protected bool CreateHomeDrive(ADobjInfo adobjin, out string objContentMsg)
    {
        objContentMsg = "";
        string retmsg;

        string tmp = adobjin.ADHomeDirve.Substring(2, adobjin.ADHomeDirve.Length - 2);
        string serverName = tmp.Substring(0, tmp.IndexOf("\\"));

        string homedrive = @adobjin.ADHomeDirve;
        adobjin.ADHomeDirve = homedrive;

        NWvarOps checksrv = new NWvarOps();
        bool homefolderbuild = checksrv.CreateFolder(out retmsg, adobjin);
        objContentMsg = retmsg;

        if (homefolderbuild)
            return true;
        else
            return false;

    }

    protected bool SetHomeACL(ADobjInfo adobjin, out string retMsg)
    {
        retMsg = "";
        string psmsg;
        int psretval;

        PSvarOps psop = new PSvarOps();
        List<string> rtnlst = psop.RunPSCmd(out psretval, out psmsg, adobjin, "fileserver");

        foreach (var itm in rtnlst)
            retMsg += itm;

        retMsg = psmsg;

        if (psretval == 0)
            return true;
        else
            return false;
    }

    protected bool CheckUserReadiness(ADobjInfo adobjin)
    {

        bool retval = false;
        int TwoSecondsInMs = 2000;
        Thread.Sleep(TwoSecondsInMs);

        string distinguishedName = WbVarious.FormatDN(adobjin.ADdistinguishedName);

        ADrwInfo adinfo = new ADrwInfo();
        if (adinfo.ADObjExists("LDAP://" + distinguishedName))
        {
            retval = true;
            return retval;
        }
        else
        {
            Thread.Sleep(TwoSecondsInMs);
            if (adinfo.ADObjExists("LDAP://" + distinguishedName))
            {
                retval = true;
                return retval;
            }
            else
            {
                retval = false;
                return retval;
            }
        }
    }

    protected bool CreateMailbox(ADobjInfo adobjin, out string objContentMsg)
    {
        string script = "";

        ADrwInfo adinfo = new ADrwInfo();
        string upnSuffix = adinfo.UpnSuffx;
        string usrUpn = adobjin.ADUserID + "@" + upnSuffix;
        string[] psCmdProps = new string[] { "", "" };

        if ((int)ViewState["mailOptionChoice"] == (int)MailOptions.Mailbox)     
        {
            script = "Enable-Mailbox -Identity " + usrUpn + " -Alias " + adobjin.ADUserID +
                " -Database " + adobjin.ADExDB + " -RetentionPolicy " + adobjin.ADExMBRetPol;
            psCmdProps = new string[] {"Name","Alias","ServerName"};
        }

        if ((int)ViewState["mailOptionChoice"] == (int)MailOptions.NoMailbox)     
        {
            script = "Enable-MailUser -Identity " + usrUpn + " -ExternalEmailAddress " + adobjin.ADMail;
            psCmdProps = new string[] { "Name", "RecipientType" };
        }

        objContentMsg = "";
        int retvalex;
        string objContentMsgex = "";

        PSwithEX PsCmnd = new PSwithEX();
        PsCmnd.PSCmd = script;               

        List<string> psCmdPropsl = new List<string>(psCmdProps);
        PsCmnd.PSCmdProps = psCmdPropsl;

        List<string> rtnList = PsCmnd.RunPSCmd(out retvalex, ref objContentMsgex);

        /*
        foreach (string itm in rtnList)
            lblAddMailbox.Text += itm + "<br />";
        */

        objContentMsg = objContentMsgex;

        if (retvalex == 0)
            return true;
        else
            return false;

    }

    protected bool SetMailboxCasPoliy(ADobjInfo adobjin, out string objContentMsg)
    {
        objContentMsg = "";
        int TwoSecondsInMs = 2000;
        Thread.Sleep(TwoSecondsInMs);

        string script = "";
        ADrwInfo adinfo = new ADrwInfo();
        string upnSuffix = adinfo.UpnSuffx;
        string usrUpn = adobjin.ADUserID + "@" + upnSuffix;

        script = "Set-CasMailbox -Identity " + adobjin.ADUserID + " -OwaMailboxPolicy " + "\"" + adobjin.ADExOwaPol + "\"";

        int retvalex;
        string objContentMsgex = "";

        PSwithEX PsCmnd = new PSwithEX();
        PsCmnd.PSCmd = script;

        string[] psCmdProps = new string[] {
            "Name"};

        List<string> psCmdPropsl = new List<string>(psCmdProps);
        PsCmnd.PSCmdProps = psCmdPropsl;

        List<string> rtnList = PsCmnd.RunPSCmd(out retvalex, ref objContentMsgex);

        /*
        foreach (string itm in rtnList)
            lblAddMailbox.Text += itm + "<br />";
        */

        objContentMsg = objContentMsgex;

        if (retvalex == 0)
            return true;
        else
            return false;
    }

    protected void UpdateLog(ADobjInfo adobjin, int rsltval, string rsltmsg)
    {
        FSUsageLogOps UsageLogEntry = new FSUsageLogOps();
        UsageLogEntry.XMLcreator = Request.LogonUserIdentity.Name;
        UsageLogEntry.XMLappVersion = WbGetParams.AppVersion;
        UsageLogEntry.XMLTimeStamp = DateTime.UtcNow.ToString();
        UsageLogEntry.XMLcodeResult = rsltval + " " + rsltmsg;
        UsageLogEntry.UpdateUsageLog(adobjin);
    }

    protected string GetNotifyMailRcpAddr()
    {
        
        string objContentMsg = "";
        ADrwInfo ADrwinfoO = new ADrwInfo();
        ADobjInfo adobjui = new ADobjInfo();
        int retval;
        int objContentNO;
        string mailto = "";
        string objsearchfilter = "user";

        string tmpusr = Request.LogonUserIdentity.Name;

        if (!string.IsNullOrEmpty(tmpusr))
        {
            //Customize here.
            if ((tmpusr.Substring(0, 4) == "ads\\") || (tmpusr.Substring(0, 4) == "ADS\\"))
            {
                tmpusr = tmpusr.Remove(0,4);
                adobjui.ADUserID = tmpusr;
            }
        }      

        List<ADobjInfo> rtnList = ADrwinfoO.RetObjValues(ref objContentMsg, out retval, out objContentNO, objsearchfilter, adobjui);

        if (retval == 0 && objContentNO > 0)
        {
            
            if (!string.IsNullOrEmpty(rtnList[0].ADMail))
            {
                mailto = rtnList[0].ADMail;
            }
        }
        else
        {
            string foo = "No mail has been sent. Mailadress was not found.";
            mailto = "";
        }

        return mailto;
    }

    protected void SendNotificationMail(string rcpaddr, string notifymsg)
    {
        NWvarOps mynotify = new NWvarOps();
        mynotify.Notifyrcp = rcpaddr;
        mynotify.Notifymsg = notifymsg;
        mynotify.SendMailNotification();
    }

    protected void colorous()
    {
        string memou = "";
        int oucnt = 0;        
        foreach (ListItem ouitm in drpdlstOUs.Items)
        {
            var sval = ouitm.Value;
            var tmpvals = sval.Split(',');
            string[] tmpa = tmpvals.ToArray();

            if (tmpa.Count() > 1)
            {
                if (memou != tmpa[2])
                {
                    memou = tmpa[2];
                    oucnt = oucnt + 1;
                    if (oucnt % 2 == 0)
                    {
                        ouitm.Attributes.Remove("class");
                        ouitm.Attributes.Add("class", "bgcolorlight");
                        ouitm.Text = ouitm.Text;
                    }
                    else
                    {
                        ouitm.Attributes.Remove("class");
                        ouitm.Attributes.Add("class", "bgcolordark");
                        ouitm.Text = ouitm.Text;
                    }
                }
                else
                {
                    if (oucnt % 2 == 0)
                    {
                        ouitm.Attributes.Remove("class");
                        ouitm.Attributes.Add("class", "bgcolorlight");
                        ouitm.Text = ouitm.Text;
                    }
                    else
                    {
                        ouitm.Attributes.Remove("class");
                        ouitm.Attributes.Add("class", "bgcolordark");
                        ouitm.Text = ouitm.Text;
                    }
                }
            }
            else
            {
                ouitm.Text = ouitm.Text;
            }

        }
    }
    protected void drpdlstOUs_TextChanged(object sender, EventArgs e)
    {
        colorous();
        colorrefresh();    
    }
    protected void colormodu(System.Web.UI.WebControls.DropDownList indrpdown)
    {
        int drpdcnt = 0;
        foreach (ListItem drpditm in indrpdown.Items)
        {
            drpdcnt = drpdcnt + 1;
            if (drpdcnt % 2 == 0)
            {
                drpditm.Attributes.Remove("class");
                drpditm.Attributes.Add("class", "bgcolordark");                
                drpditm.Text = drpditm.Text;
            }
            else
            {
                drpditm.Attributes.Remove("class");
                drpditm.Attributes.Add("class", "bgcolorlight");
                drpditm.Text = drpditm.Text;
            }
        }
    }
    protected void drpdlstExDBs_TextChanged(object sender, EventArgs e)
    {
        colormodu(drpdlstExDBs);
    }
    protected void drpdlstExMbOwaPols_TextChanged(object sender, EventArgs e)
    {
        colormodu(drpdlstExMbOwaPols);
    }
    protected void drpdlstExMbRetPols_TextChanged(object sender, EventArgs e)
    {
        colormodu(drpdlstExMbRetPols);
    }
    protected void drpdlstDFSHome_TextChanged(object sender, EventArgs e)
    {
        colormodu(drpdlstDFSHome);
    }
    
    protected void lbtnRestartApp_Click(object sender, EventArgs e)
    {        
        clear_fields();        
        Page.Response.Redirect(Page.Request.Url.ToString(), false);
    }
 

}